﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.SqlCommand;
using NHibernate;

namespace Apollo
{
    /// NOLOCK solution with interceptor
    public class NoLockInterceptor : EmptyInterceptor, IInterceptor
    {
        public NoLockInterceptor() : base() { }

        SqlString NHibernate.IInterceptor.OnPrepareStatement(SqlString sql)
        {
            // ignore other statements
            if (!sql.StartsWithCaseInsensitive("select"))
                return sql;

            // parse SELECT queries
            SqlString noLockQueryString = sql;

            int indexOfFirstJoin = noLockQueryString.IndexOfCaseInsensitive("left outer join");
            if (indexOfFirstJoin > 0)
            {
                SqlString firstPart = noLockQueryString.Substring(0, indexOfFirstJoin);
                SqlString lastPart = noLockQueryString.Substring(indexOfFirstJoin);

                noLockQueryString = firstPart
                    .Append(" with(nolock) ")
                    .Append(lastPart);
            }

            noLockQueryString = noLockQueryString.Replace(" on ", " with(nolock) on ");

            return noLockQueryString;
        }
    }
}
